package org.javason.jsonrpc;

import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.Arrays;

import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.javason.util.Metrics;
import org.javason.util.MetricsConfiguration;


public class TestJsonRpcMetrics extends AbstractJsonRpcTestCase {
	
	public void testJsonInterface8() throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
		(new MetricsConfiguration()).setGlobalMinThreshold(0.0);
		// evil reflection field access..
		Field threshold = Metrics.class.getDeclaredField("_threshold");
		threshold.setAccessible(true);
		Object oldThreshold = threshold.get(Metrics.class);
		threshold.set(Metrics.class, new Double(0));
		
		
		Logger.getLogger(Metrics.class).removeAllAppenders();
		
		StringWriter strWriter = new StringWriter();
		Logger.getLogger(Metrics.class).addAppender(new WriterAppender(new SimpleLayout(), strWriter));
		
		System.out.println("RUNNING TestJsonRpcMetrics.testJsonInterface8()");
Logger.getLogger(Metrics.class).error("BALHALHFDLKAHJFSL");
		try {
			String[] testInput = new String[] { "hi", "there" };
			JSONObject responseObj = callMethod(new ArrayService(), "testArrayIn", Arrays.asList(testInput));
			
			System.out.println("---- metrics output ---");
			System.out.println(strWriter.toString());
			
			String[] result = strWriter.toString().split("Metrics.*\n");
			assertEquals(3, result.length);
			assertTrue(responseObj.has("result"));
			assertTrue(JSONUtils.isNull(responseObj.opt("error")));
			assertEquals(99, responseObj.getJSONArray("result").get(0));
		} catch (Exception e1) {
			e1.printStackTrace();
			assertTrue(false);
		} finally {
			threshold.set(Metrics.class, oldThreshold);
		}
		System.out.println("--");
	}
}
